<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\Config;
use App\Repository\ConfigRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiConfigController extends BaseController4Restful
{
    /**
     * @Route("/api/configs", name="apiGetConfigs",methods={"GET","POST"})
     */
    public function apiGetConfigs(ConfigRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $Config Config*/
                $Config = $this->createEntity($data,Config::class);
                $this->myEm()->persist($Config);$this->myEm()->flush();
                return $this->json_out(200,"创建成功", $Config);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array(),array(),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/configs/{id}", name="apiAddConfigs",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateConfigs(Config $Config,Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($Config);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $Config Config*/
                $Config = $this->updateEntity($data,Config::class,$Config);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($Config);$this->myEm()->flush();
        return $this->json_out(200,"获取成功", $Config);
    }

    /**
     * @Route("/api/get_config", name="apiGetConfigByK")
     */
    public function apiGetConfigByK(
        ConfigRepository $configRepository
    )
    {
        $data = $this->getRequestData();
        $code = $data["code"];
        $config = $configRepository->findOneBy(array("k"=>$code));
        return $this->json_out(1,"获取成功", $config);
    }
}
